﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentData;
using System.Dynamic;
using System.Data;

namespace Eleanor.DAL
{
    public class PaintingDAL : DALBase
    {
        public int Insert(dynamic painting)
        {
            IStoredProcedureBuilder command = DefaultContext.StoredProcedure("PaintingInsert");
            command.Parameter("Painting", painting.Title)
                   .Parameter("Painting", painting.PaintingNumber)
                   .Parameter("Painting", painting.Description)
                   .Parameter("Painting", painting.ImageUrl)
                   .Parameter("Painting", painting.Tags)
                   .Parameter("Painting", painting.Authorships)
                   .Parameter("Painting", painting.Subjects)
                   .Parameter("Painting", painting.CreateDate)
                   .Parameter("Painting", painting.UpdateDate)
                   .Parameter("Painting", painting.HandEnable)
                   .Parameter("Painting", painting.PrinterEnable)
                   .ParameterOut("PaintingId", DataTypes.Int32, 4);
            command.Execute();
            return command.ParameterValue<int>("PaintingId");
        }

        /// <summary>
        /// 获取Painting实体
        /// </summary>
        /// <param name="paintingNumber"></param>
        /// <returns></returns>
        public dynamic Select(string paintingNumber)
        {
            const string sql = @"select * from Painting where painting_number=@0";
            return CustomMapperUsingDynamic(DefaultContext.Sql(sql).Parameters(paintingNumber).QuerySingle<dynamic>());
        }

        public dynamic Select(int paintingId)
        {
            const string sql = @"select * from Painting where painting_id=@0";
            return CustomMapperUsingDynamic(DefaultContext.Sql(sql).Parameters(paintingId).QuerySingle<dynamic>());
        }

        public List<dynamic> SelectAll()
        {
            const string sql = @"select * from Painting";
            List<dynamic> unConvertedList = DefaultContext.Sql(sql).QueryMany<dynamic>();
            List<dynamic> convertedList = new List<dynamic>();
            foreach (dynamic item in unConvertedList)
            {
                convertedList.Add(CustomMapperUsingDynamic(item));
            }
            return convertedList;
        }

        public int GeneratePaintingId(string paintingNumber)
        {
            return DefaultContext.Insert("painting").Column("painting_number", paintingNumber).ExecuteReturnLastId<int>();
        }

        public int Update(dynamic painting)
        {
            IStoredProcedureBuilder iStoredProcedureBuilder = DefaultContext.StoredProcedure("PaintingUpdate")
                   .Parameter("Title", painting.Title as string)
                   .Parameter("PaintingNumber", painting.PaintingNumber as string)
                   .Parameter("Description", painting.Description as string)
                   .Parameter("ImageUrl", painting.ImageUrl as string)
                   .Parameter("Tags", painting.Tags as string)
                   .Parameter("Authorships", painting.Authorships as string)
                   .Parameter("Subjects", painting.Subjects as string)
                   .Parameter("HandEnable", (bool)painting.HandEnable)
                   .Parameter("PrinterEnable", (bool)painting.PrinterEnable)
                   .Parameter("PaintingId", (int)painting.PaintingId)
                   .Parameter("Frames", (int)painting.Frames);
            return iStoredProcedureBuilder.Execute();
        }

        public int Import(dynamic painting)
        {
            var command = DefaultContext.StoredProcedure("PaintImport", (ExpandoObject)painting)
                    .AutoMap().ParameterOut("PaintingId", DataTypes.Int32, 4);
            command.Execute();
            return command.ParameterValue<int>("PaintingId");
        }

        public dynamic Select(dynamic condition, int pageIndex, int pageSize)
        {
            dynamic result = new ExpandoObject();
            condition.PageSize = pageSize;
            condition.PageIndex = pageIndex;
            var command = DefaultContext.StoredProcedure("PaintingSearch", (ExpandoObject)condition)
                .AutoMap().ParameterOut("RowCount", DataTypes.Int32, 4);
            result.PaintingList = command.QueryMany<dynamic>();
            result.RowCount = command.ParameterValue<int>("RowCount");
            return result;
        }

        public List<dynamic> SelectRelated(int paintingId)
        {
            return DefaultContext.StoredProcedure("PaintingRelated")
                .Parameter("PaintingId", paintingId)
                .QueryMany<dynamic>();
        }

        public DataTable SelectMulti(string paintingNummbers)
        {
            if (string.IsNullOrWhiteSpace(paintingNummbers))
            {
                return new DataTable();
            }
            string[] arr = paintingNummbers.Split(',');
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = "'" + arr[i].Trim() + "'";
            }
            string newPns = string.Join(",", arr);
            return DefaultContext.Sql(string.Format("select painting_number as PaintingNumber, Title, ISNULL(image_url, '') as ImageUrl from painting where painting_number in ({0})", newPns)).QuerySingle<DataTable>();
        }

        public List<dynamic> SelectAllFrames()
        {
            var command = DefaultContext.Sql("select distinct isnull(frames,0) as Frame from painting");
            return command.QueryMany<dynamic>();
        }

        private dynamic CustomMapperUsingDynamic(dynamic row)
        {
            if (row == null)
            {
                return null;
            }
            dynamic painting = new ExpandoObject();
            painting.PaintingId = row.painting_id;
            painting.PaintingNumber = row.painting_number;
            painting.Title = row.title;
            painting.Description = row.description;
            painting.ImageUrl = row.image_url;
            painting.Tags = row.tags;
            painting.Authorships = row.authorships;
            painting.Subjects = row.subjects;
            painting.HandEnable = row.hand_enable ?? false;
            painting.PrinterEnable = row.printer_enable ?? false;
            painting.Frames = row.frames ?? 0;
            painting.UpdateDate = row.update_date ?? DateTime.Now;
            return painting;
        }
    }
}